package com.example.student;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.database.DatabaseHelper;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import de.hdodenhof.circleimageview.CircleImageView;

public class Profile extends Fragment {

    private static final int PICK_IMAGE = 1; // 请求码
    private CircleImageView ivAvatar;
    private TextView tvName, tvStudentId, tvCollege, tvMajor, tvGrade, tvPhone;
    private ImageButton btnChangeAvatar;
    private ImageButton btnEditPhone;
    private DatabaseHelper dbHelper;
    private int studentId; // 当前学生的学号

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载布局文件
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        // 初始化视图
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvPhone = view.findViewById(R.id.tv_phone);
        tvName = view.findViewById(R.id.tv_name);
        tvStudentId = view.findViewById(R.id.tv_student_id);
        tvCollege = view.findViewById(R.id.tv_college);
        tvMajor = view.findViewById(R.id.tv_major);
        tvGrade = view.findViewById(R.id.tv_grade);
        btnChangeAvatar = view.findViewById(R.id.btn_change_avatar);
        btnEditPhone = view.findViewById(R.id.btn_edit_phone);

        // 初始化 DatabaseHelper
        dbHelper = new DatabaseHelper(getActivity());

        // 获取传递的学号
        Bundle bundle = getArguments();

        //加载数据
        if (bundle != null) {
            studentId = bundle.getInt("student_id", -1);
            Log.d("student_id", String.valueOf(studentId));
            if (studentId != -1) {
                // 查询用户信息
                Cursor cursor = dbHelper.getUserInfo(studentId);
                if (cursor != null && cursor.moveToFirst()) {
//                    // 打印调试信息
//                    String[] columnNames = cursor.getColumnNames();
//                    for (String columnName : columnNames) {
//                        int columnIndex = cursor.getColumnIndex(columnName);
//                        if (columnIndex != -1) {
//                            Log.d("CursorDebug", columnName + ": " + cursor.getString(columnIndex));
//                        }
//                    }

                    // 获取列索引
                    int nameIndex = cursor.getColumnIndex("name");
                    int studentIdIndex = cursor.getColumnIndex("student_id");
                    int collegeIndex = cursor.getColumnIndex("college");
                    int majorIndex = cursor.getColumnIndex("major");
                    int gradeIndex = cursor.getColumnIndex("grade");
                    int phoneIndex = cursor.getColumnIndex("phone");

                    // 设置数据到视图
                    if (nameIndex != -1) {
                        tvName.setText("姓名：" + cursor.getString(nameIndex));
                    }
                    if (studentIdIndex != -1) {
                        tvStudentId.setText("学号：" + cursor.getInt(studentIdIndex));
                    }
                    if (collegeIndex != -1) {
                        tvCollege.setText("学院：" + cursor.getString(collegeIndex));
                    }
                    if (majorIndex != -1) {
                        tvMajor.setText("专业：" + cursor.getString(majorIndex));
                    }
                    if (gradeIndex != -1) {
                        tvGrade.setText("年级：" + cursor.getString(gradeIndex));
                    }
                    if (phoneIndex != -1) {
                        tvPhone.setText( cursor.getString(phoneIndex));
                    }
                }
                if (cursor != null) {
                    cursor.close();
                }
            }
        }


        // 设置头像修改按钮的点击事件
        btnChangeAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

        // 设置手机号修改按钮的点击事件
        btnEditPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditPhoneDialog();
            }
        });

        return view;
    }

    // 打开相册选择图片
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE);
    }

    // 处理选择的图片
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == getActivity().RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            ivAvatar.setImageURI(selectedImage); // 设置头像
        }
    }

    // 弹出修改手机号的对话框
    private void showEditPhoneDialog() {
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getActivity());
        builder.setTitle("修改手机号");

        // 输入框
        final androidx.appcompat.widget.AppCompatEditText input = new androidx.appcompat.widget.AppCompatEditText(getActivity());
        input.setText(tvPhone.getText().toString());
        builder.setView(input);

        // 保存按钮
        builder.setPositiveButton("保存", (dialog, which) -> {
            String newPhone = input.getText().toString();
            if (!newPhone.isEmpty()) {
                tvPhone.setText(newPhone); // 更新手机号
                // 更新数据库中的手机号
                dbHelper.updatePhone(studentId, newPhone,0);
            }
        });

        // 取消按钮
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }
}